
package com.sausageking.server;

import java.util.logging.Logger;

import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.sausageking.client.MerchantService;
import com.sausageking.server.dao.GenericDao;
import com.sausageking.server.dao.MerchantDao;
import com.sausageking.server.dao.MerchantDaoImpl;
import com.sausageking.shared.Merchant;
import com.sausageking.shared.YearPassCodes;

@SuppressWarnings("serial")
public class MerchantServiceImpl extends RemoteServiceServlet
    implements
      MerchantService {

  private static final Logger log = Logger.getLogger(MerchantServiceImpl.class
      .getName());

  private MerchantDao dao = new MerchantDaoImpl();

  @Override
  public Merchant insert(Merchant merchant) throws IllegalArgumentException {
    Merchant inserted = dao.insert(merchant);
    log.info(inserted.toString());
    return inserted;
  }

  @Override
  public Merchant update(Merchant merchant) throws IllegalArgumentException {
    Merchant updated =  dao.update(merchant);
    log.info(updated.toString());
    return updated;
  }

  @Override
  public Merchant getByEmail(String email) throws IllegalArgumentException {
    GenericDao<Merchant> dao = new GenericDao<Merchant>(Merchant.class);
    Merchant merchant = dao.getByProperty("email", email);

    if (merchant == null) {
      throw new IllegalArgumentException("Merchant with email:" + email
          + " can not be found.");
    }
    merchant.setSalt(null);
    return merchant;
  }

  @Override
  public Merchant getById(Long id) throws IllegalArgumentException,
      EntityNotFoundException {
    return dao.getById(id);
  }

  @Override
  public YearPassCodes getPassCodeBook(String merchant, int year)
      throws EntityNotFoundException {
    return new PassCodeGeneratorImpl().generatePassCodeBook(merchant, year);
  }
}
